package com.xdb.sqlparser.ast;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.xdb.sqlparser.visitor.SQLAstVisitor;
/**
 * 抽象的Sql对象
 * 
 * @author woate
 *
 */
public abstract class AbstractSQLObjectImpl implements SQLObject {

	private SQLObject parent;

	private Map<String, Object> attributes;

	public AbstractSQLObjectImpl() {
	}
	/**
	 * 将accept0(SQLAstVisitor)推迟到子类实现
	 */
	public final void accept(SQLAstVisitor visitor) {
		if (visitor == null) {
			throw new IllegalArgumentException();
		}
		// 调用访问者的前置访问方法
		visitor.preVisit(this);
		// 推迟访问accept0
		accept0(visitor);
		// 调用访问者的后置访问方法
		visitor.postVisit(this);
	}

	protected abstract void accept0(SQLAstVisitor visitor);

	protected final void acceptChild(SQLAstVisitor visitor, List<? extends SQLObject> children) {
		if (children == null) {
			return;
		}

		for (SQLObject child : children) {
			acceptChild(visitor, child);
		}
	}
	/**
	 * 检查是否接受子节点
	 * @param visitor
	 * @param child
	 */
	protected final void acceptChild(SQLAstVisitor visitor, SQLObject child) {
		if (child == null) {
			return;
		}
		child.accept(visitor);
	}

	public void output(StringBuffer buf) {
		buf.append(super.toString());
	}

	public String toString() {
		StringBuffer buf = new StringBuffer();
		output(buf);
		return buf.toString();
	}

	public SQLObject getParent() {
		return parent;
	}

	public void setParent(SQLObject parent) {
		this.parent = parent;
	}

	public Map<String, Object> getAttributes() {
		if (attributes == null) {
			attributes = new HashMap<String, Object>(1);
		}

		return attributes;
	}

	public Object getAttribute(String name) {
		if (attributes == null) {
			return null;
		}

		return attributes.get(name);
	}

	public void putAttribute(String name, Object value) {
		if (attributes == null) {
			attributes = new HashMap<String, Object>(1);
		}

		attributes.put(name, value);
	}

	public Map<String, Object> getAttributesDirect() {
		return attributes;
	}

}
